
import { Button, Menu } from 'antd';
import React, { useState, useEffect } from 'react';
import * as api from "@/api/permission"
//引入路由配置
import routes from "../router/index"
import { useNavigate } from 'react-router-dom';

const mapManu = (data) => {
    //递归处理数据
    let menuList = []
    const recursion = (data) => {
        //console.log(data);
        data.forEach(item => {
            let obj = {
                label: item.name,
                key: item.id
            }
            if (item.children) {
                obj.children = mapManu(item.children)
            }
            menuList.push(obj)
        })
    }
    recursion(data)
    return menuList
}
const UserMenu = () => {
    let [items, setItems] = useState([])
    let navigate = useNavigate()
    // useEffect(() => {
    //     api.login()
    //         .then(res => {
    //             //console.log(res);
    //             //简单存一下token
    //             localStorage.setItem('qf-token', res.data.token)
    //         })
    //         .then(() => {
    //             api.getMenu()
    //                 .then(res => {
    //                     //console.log(res);
    //                     //数据处理，name映射成label
    //                     setItems(mapManu(res.data.menuList))
    //                 })
    //         })
    // })

    useEffect(() => {
        //根据本地路由配置生成菜单
        //取出routes中 路径=="/"的childeren选项
        let target = routes.find(item => item.path === "/")
        // let newRoutes = target.children.map(item => ({
        //     label: item.label,
        //     key: item.key
        // }))
        setItems(target.children)
    })

    //点击菜单按钮进行跳转
    const handleClick = (item, key) => {
        console.log(item);
        //处理路径
        let path = '/' + item.keyPath.reverse().join('/')
        console.log(path);
        navigate(path)
    }

    return (
        <div style={{
            width: "100%"
        }}>
            <Menu
                defaultSelectedKeys={['8']}  //默认选中id
                defaultOpenKeys={['2']}   //默认展开id
                mode="inline"
                theme="dark"
                onClick={handleClick}
                items={items}
            />
        </div>
    );
};

export default UserMenu;